package com.ai.sml.filter;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;

import com.ai.sml.util.DateUtil;
import com.ai.sml.util.StringUtil;
import com.ai.sml.util.WebUtils;

public class AccessLogFilter implements Filter {
	//private static final Logger logger = LoggerFactory.getActionLog(LoginAction.class);
	//private static final Log logger = LogFactory.getLog(AccessLogFilter.class);
	private static final Log accessLog = LogFactory.getLog("accessLog");

	public void destroy() {

	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
//		// todo sessionid? ip/user action url
//		Session session = SecurityUtils.getSubject().getSession();//shiro session
//		
//		String sessionId = req.getSession().getId();// session
//		String refer = req.getHeader("Referer");
//		String ua = req.getHeader("User-Agent");
//		
//		/*---------------Start---------------*/
//		String userIP = WebUtils.getCurrentIP(req);//ip
////		String userID = (String) session.getAttribute("openid");//微信id FIXME
////		if("1".equals(userID) || StringUtil.isEmpty(userID)){//获取已登录账号或者sessionid
////			Object merchantInfo = session.getAttribute("merchantInfo");
////			if(merchantInfo != null){
////				JSONObject loginUser = JSONObject.fromObject(merchantInfo);
////				userID = loginUser.getString("userLoginId");
////			}else{
////				userID = sessionId;
////			}
////		}
//		String User_WeChat_ID = (String) session.getAttribute("openid");//微信id
//		String User_Login_id = null;
//		Object merchantInfo = session.getAttribute("merchantInfo");
//		if(merchantInfo != null){
//			JSONObject loginUser = JSONObject.fromObject(merchantInfo);
//			User_Login_id = loginUser.getString("userLoginId");
//		}
//				
//		String requestTimeStamp = DateUtil.date2String(new Date());//请求时间戳
//		String responseTimeStamp = "";//响应时间戳 
//		String userOrigin = getClientType(req);//客户端类型
//		String userReference = refer == null ? "" : refer;
//		String requestURL = req.getRequestURL().toString();
//		String browserVersion = getBrowserVersion(ua);//浏览器
//		String browserPlatform = getOS(ua);//操作系统
//		String isMobileDevice = ua.contains("Mobile") ? "是" : "否";
//		String mobileDeviceModel = getModel(ua);//设备型号
//		/*----------------End--------------*/
//		
////		String method = req.getMethod();
////		System.out.println(">>>>>>>>>>>>>>>>>>>>>>>");
////		System.out.println(req.getSession().getId());
////		System.out.println(ua);
//
//		StringBuilder msg = new StringBuilder("");
//		msg.append(userIP).append("|").append(sessionId).append("|")
//				.append(User_WeChat_ID).append("|").append(User_Login_id).append("|")
//				.append(requestTimeStamp).append("|").append(responseTimeStamp)
//				.append("|").append(userOrigin).append("|")
//				.append(userReference).append("|").append(requestURL)
//				.append("|").append(browserVersion).append("|")
//				.append(browserPlatform).append("|").append(isMobileDevice)
//				.append("|").append(mobileDeviceModel);
//		//logMsg(tmpLogFile, userIP + " - - [" + DateUtil.date2String(new Date()) + "]\t[" + sessionId + "]\t" + method + " " + requestURL);
//		//logMsg(tmpLogFile, msg.toString());
//		accessLog.info(msg.toString());
		chain.doFilter(req, res);
	}

	/**
	 * 将信息记录到日志文件
	 * 
	 * @param logFile
	 *            日志文件
	 * @param mesInfo
	 *            信息
	 * @throws IOException
	 */
	public void logMsg(File logFile, String mesInfo) throws IOException {
		if (logFile == null) {
			throw new IllegalStateException("logFile can not be null!");
		}
		Writer txtWriter = new FileWriter(logFile, true);
		txtWriter.write(mesInfo);
		txtWriter.flush();
		txtWriter.close();
	}
	
	private String getModel(String userAgent){//windows phone--
		if(userAgent.contains("Mac OS")){//Apple Like
			if(userAgent.contains("iPhone")){
				return "iPhone";
			}else if(userAgent.contains("iPad")){
				return "iPad";
			}else if(userAgent.contains("iPod")){
				return "iPod";
			}
		}
		String regex = ";\\s?([^;]+?)\\s?(Build)?/";
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(userAgent);
		String model = "";
		if(matcher.find()){
			model = matcher.group(1).trim().replace(") AppleWebKit", "");
		}
		return model;
	}
	
	private String getOS(String userAgent){
		String model = "";
		String regex = "U; (.+?);";
		if(userAgent.contains("iPhone")){
			regex = "iPhone; CPU (.+?) like Mac OS";
		}else if(!userAgent.contains("Android")){
			if(userAgent.contains("Windows")){
				return "Windows";
			}else{
				return "Unix";
			}
		}
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(userAgent);
		if(matcher.find()){
			model = matcher.group(1).trim();
		}
		
		return model;
	}
	
	private String getWxVersion(String userAgent){
		String model = "";
		String regex = "MicroMessenger/(.+?)($| .+)";
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(userAgent);
		if(matcher.find()){
			model = matcher.group(1).trim();
		}
		
		return model;
	}
	
	private String getBrowserVersion(String userAgent){
		String model = "";
		String regex = "(MicroMessenger/(.+?))($| .+)";
		if(!userAgent.contains("MicroMessenger")){
			regex = "((Chrome|\\w+Browser|Firefox|Safari)/(.+?))($| .+)";//IE baidu FIXME
		}
		Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(userAgent);
		if(matcher.find()){
			model = matcher.group(1).trim();
		}
		
		return model;
	}
	
	private String getClientType(HttpServletRequest req){//客户端类型：微信/浏览器
		if(StringUtil.isNotEmpty(req.getHeader("wxuserAgent"))){//windows phone特殊处理
			return "微信";
		}else{
			return req.getHeader("User-Agent").contains("MicroMessenger") ? "微信" : "浏览器";
		}
	}

	public void init(FilterConfig config) throws ServletException {

	}

}
